using System.Collections.Specialized;
using System.Web.Mvc;
using Castle.Services.Transaction;
using WineCellar.Web.Security;

namespace WineCellar.Web.Controllers
{
    [Authorization]
    [HandleError(View = "Error")]
    [Transactional]
    public class WineCellarController : Controller
    {
        /// <summary>
        /// Puts the request values that have to do with ExtJs filtering in a namevaluecollection
        /// so that we can use the SmartBinder to put these values in the searchobject
        /// </summary>
        /// <returns>Namevaluecollection with search field and search value</returns>
        protected NameValueCollection PutRequestFilterValuesInNameValueCollection()
        {
            var formValues = new NameValueCollection();
            for (var i = 0; i < 100; i++)
            {
                var field = this.ReadFromRequest("filter[" + i + "][field]");
                if (!string.IsNullOrEmpty(field))
                {
                    field = field.Replace(".", "");
                    var value = this.ReadFromRequest("filter[" + i + "][data][value]");
                    var comparison = this.ReadFromRequest("filter[" + i + "][data][comparison]");
                    switch (comparison)
                    {
                        case "gt":
                            formValues.Add(field + "IsLargerThan", value);
                            break;
                        case "lt":
                            formValues.Add(field + "IsSmallerThan", value);
                            break;
                        case "eq":
                            formValues.Add(field + "Is", value);
                            break;
                        default:
                            formValues.Add(field, value);
                            break;
                    }
                    if (value.IndexOf(".") > -1)
                    {
                        formValues.Add(field, value.Remove(value.IndexOf(".")));
                    }
                }
                else
                {
                    break;
                }
            }
            return formValues;
        }

        protected string ReadFromRequest(string key)
        {
            return Request[key];
        }
    }
}